package com.xiaobawang.homework1226.code.aop;
import com.xiaobawang.homework1226.code.LogAnno.LogAnno;
import com.xiaobawang.homework1226.code.component.HttpContextUtil;
import com.xiaobawang.homework1226.entity.Log;
import com.xiaobawang.homework1226.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Order(3)
@Component
@Aspect
public class LogAopect {

    @Autowired
    private LogMapper logMapper;

    /**
     * author: Synhard
     * description: Record the method called by the custom annotation to the database through a circular notification
     * create time: 2019/12/26 8:57:00
     * last modified: 2019/12/26 8:57:00
     * **/
    @Around("@annotation(com.xiaobawang.homework1226.code.LogAnno.LogAnno)")
    public Object aroundAdive(ProceedingJoinPoint pip) throws Throwable {

        // 获取相关的方法签名
        MethodSignature methodSignature = (MethodSignature)pip.getSignature();

        // 获取方法名称
        Method method = methodSignature.getMethod();

        // 获取注解
        LogAnno logAnno = method.getAnnotation(LogAnno.class);

        // 获取操作描述
        String operType = logAnno.operateType();

        // 创建日志对象
        Log log = new Log();

        log.setOperation(operType);
        log.setUsername("Synhard");
        log.setIp(HttpContextUtil.getIpAddress());

        String classname = pip.getTarget().getClass().getName();
        String m = methodSignature.getName();

        log.setMethod(classname + "." + m + "()");

        Object[] args = pip.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String [] paramName = u.getParameterNames(method);
        if (args != null && paramName != null) {
            String param = "";
            for (int i = 0; i < args.length; i++) {
                param += "  " + paramName[i] + ":" + args[i];
            }
            log.setParams(param);
        }

        // 获取执行方法的时间
        Object result = null;
        try {
            long beginTime = System.currentTimeMillis();
            result = pip.proceed(); // 执行调用接口的方法
            long endTime = System.currentTimeMillis()-beginTime;
            log.setTime(endTime);
        } catch (Exception e) {

        }
        log.setCreatetime(new Date());
        logMapper.insert(log);
        return result;
    }

}
